package com.lrm.web.admin;

import com.lrm.biz.ITypeBiz;
import com.lrm.pojo.Type;
import com.lrm.util.Result;
import com.lrm.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2017/11/30.
 * @Modified By:
 */
@RestController
@RequestMapping("admin")
public class TypeController {

    @Autowired
    private ITypeBiz typeService;

    /**
     * 分页查询列表并，默认是10条，并按ID倒序排列
     * @param pageable
     * @return
     */
    @GetMapping("listTypePages")
    public Result listPages(@PageableDefault(size = 10,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable){
        Page<Type> types = typeService.pagelistType(pageable);
        return ResultUtil.success(types);
    }

    @PostMapping("addType")
    public Result addType(@Valid Type type){
        Type byname = typeService.findByname(type.getName());
        if (byname!=null) {
            return ResultUtil.error(2,"类型已存在，不能重复添加");
        }
        Type type1 = typeService.saveType(type);
        if (type1==null) {
            return ResultUtil.error(2,"保存失败");
        }
        return ResultUtil.success(type1);
    }

    @GetMapping("delType/{id}")
    public Result delType(@PathVariable Long id){
        Boolean b = typeService.delType(id);
        if (b) {
            return ResultUtil.success();
        }
        return ResultUtil.error(2,"删除失败");
    }

    @PostMapping("updataType/{id}")
    public Result updataType(@PathVariable Long id,@Valid Type type){
        Type byname = typeService.findByname(type.getName());
        if (byname!=null) {
            return ResultUtil.error(2,"类型已存在，不能重复添加");
        }
        Type type1 = typeService.upadtaType(id, type);
        if (type1!=null) {
            return ResultUtil.success(type1);
        }
        return ResultUtil.error(2,"修改失败");
    }
}
